//
//  FansAndAttentionViewController.m
//  iOS-CtrlV
//
//  Created by 龚 杰 on 12-12-20.
//  Copyright (c) 2012年 Wang Li. All rights reserved.
//

#import "FansAndAttentionViewController.h"
#import "AsyncImageView.h"
#import "FansAndAttentionListModel.h"
#import "MainTabBarController.h"
#import "OwnViewController.h"
#import "LoginViewController.h"

#define MAXPAGENUM 20

@interface FansAndAttentionViewController ()

@end

@implementation FansAndAttentionViewController
@synthesize user_id = m_user_id;
@synthesize m_TargetID;
//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization
//    }
//    return self;
//}
- (id)initType:(NSUInteger)_type
{
    if (self = [super init]) {
        m_type = _type;
        m_page = 1;
        isPage = NO;
        isNextAndUp = 0;
        isLook = YES;
        m_fadate = [[NSMutableArray alloc] init];
      
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor colorWithRed:193/255.f green:193/255.f blue:193/255.f alpha:1]];
    

    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
	// Do any additional setup after loading the view.
    _BackBttBarItem =[UIButton buttonWithType:UIButtonTypeCustom];
    _BackBttBarItem.frame =CGRectMake(0, 0, 44, 44);
    [_BackBttBarItem setImage:[UIImage imageNamed:@"navback.png"] forState:UIControlStateNormal];
    [_BackBttBarItem addTarget:self action:@selector(navBackBtt) forControlEvents:UIControlEventTouchUpInside];
    [_BackBttBarItem retain];
    
    
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        [self.navigationController.navigationBar setBackgroundImage:tAppDel.m_MidNavImg forBarMetrics: UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = NO;
        
//        UIImageView* tImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navshadow.png"]];
//        tImgView.frame =CGRectMake(0, 44, 320, 5);
//        [self.navigationController.navigationBar addSubview:tImgView];
//        [tImgView release];
    }
    m_fandaTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,
                                                                    self.view.frame.size.height)
                                                   style:UITableViewStylePlain];
    [m_fandaTableView setDataSource:self];
    [m_fandaTableView setDelegate:self];
    
    [m_refreshHeaderView release];
    m_refreshHeaderView =nil;
    m_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - m_fandaTableView.bounds.size.height, m_fandaTableView.frame.size.width, m_fandaTableView.frame.size.height)];
    m_refreshHeaderView.delegate = self;
    [m_fandaTableView addSubview:m_refreshHeaderView];
    [m_refreshHeaderView refreshLastUpdatedDate];
    [self.view addSubview:m_fandaTableView];
    
    m_myhttp  = [[MyHttpProcessor alloc] init];
    m_myhttp.delegate = self;

    [self requestPageData];
    [self addHudLoad];

}

-(void) viewWillAppear:(BOOL)animated
{
    if ([_BackBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:_BackBttBarItem];
    }
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_BackBttBarItem removeFromSuperview];
}
-(void) navBackBtt
{
//     self.tabBarController.tabBar.hidden = NO;
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 分页
- (void)ChangeNextPage:(UIButton*)ibutton
{
    
}
- (void)ChangeUpPage:(UIButton*)ibutton
{
    
}
- (void)Pagingrequest;
{
    if (isPage) {
        if (isNextAndUp == 1) {
            m_page++;
        }else if(isNextAndUp == 2){
            if (m_page>1) {
                m_page--;
            }
        }
        [self requestPageData];
    }else{
        
    }
  
}
- (void)requestPageData
{

    if (isLook) {
        isLook = NO;
        if (m_type == FANSTYPE) {
            [m_myhttp RequestFansListGet:m_user_id.intValue ID:m_TargetID start:m_page limit:MAXPAGENUM];
            m_myhttp.delegate = self;
         
        }else{
            [m_myhttp RequestAttentionListGet:m_user_id.intValue ID:m_TargetID start:m_page limit:MAXPAGENUM];
            m_myhttp.delegate = self;
        }
  
    }
    isNextAndUp = 0;
}
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FansAndAttentionListModel* famModel = [m_fadate objectAtIndex:indexPath.row];
    if (famModel != nil) {
        MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
        tMainTabBar.m_TabbarCustom.hidden =YES;
        OwnViewController* tNextVC = [[OwnViewController alloc] initUesrID:famModel.fans_id];
        tNextVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tNextVC animated:YES];
        [tNextVC release];
    }
}

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"%d",[m_fadate count]);
    return [m_fadate count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString* tSStrCell = @"FansAndAttentioncell";
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tSStrCell];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tSStrCell] autorelease];
       tCell.selectionStyle = UITableViewCellSelectionStyleNone;
        AsyncImageView* haedview = [[AsyncImageView alloc] initWithFrame:CGRectMake(5, 6, 32, 32)];
        haedview.tag =100;
        [tCell.contentView addSubview:haedview];
        [haedview release];
        
        UIButton* ibutton = [UIButton buttonWithType:UIButtonTypeCustom];
        ibutton.backgroundColor = [UIColor clearColor];
        ibutton.tag = 1001;
        ibutton.frame = CGRectMake(5, 6, 32, 32);
        [ibutton addTarget:self action:@selector(changeMydata:) forControlEvents:UIControlEventTouchUpInside];
        [tCell.contentView addSubview:ibutton];
 
        UILabel* name = [[UILabel alloc] initWithFrame:CGRectMake(52, 14, 120, 16)];
        name.tag = 101;
        name.backgroundColor = [UIColor clearColor];
        name.font = [UIFont boldSystemFontOfSize:15.0f];
        name.textColor = [UIColor colorWithRed:45/255.0f green:45/255.0f blue:45/255.0f alpha:1.0f];
        [tCell.contentView addSubview:name];
        [name release];
        
        
        UIButton* guan = [UIButton buttonWithType:UIButtonTypeCustom];
        guan.tag = 1000;
        [guan setBackgroundImage:[UIImage imageNamed:@"forward_button"] forState:UIControlStateNormal];
        guan.frame = CGRectMake(tCell.frame.size.width-63, 8, 53, 28);
        [guan setTitleColor:[UIColor colorWithRed:83/255.0f green:83/255.0f blue:83/255.0f alpha:1.0f] forState:UIControlStateNormal];
        guan.titleLabel.font = [UIFont systemFontOfSize:11.0f];
        [guan addTarget:self action:@selector(ChangeFButton:) forControlEvents:UIControlEventTouchUpInside];
        [tCell.contentView addSubview:guan];
        
    }
    FansAndAttentionListModel* famModel = [m_fadate objectAtIndex:indexPath.row];

    AsyncImageView* asyimg = (AsyncImageView*)[tCell viewWithTag:100];
    asyimg._imageRequestURL = famModel.fans_user_headimageurl;
    asyimg.m_BoolSetImage = YES;
    [asyimg customLoadImageFromURL];
    
    UILabel* name1 = (UILabel*)[tCell viewWithTag:101];
    name1.text = famModel.fans_user_name;

    UIButton* ibutton = (UIButton*)[tCell viewWithTag:1000];
    ibutton.tag = indexPath.row;
    
    UIButton* haed = (UIButton*)[tCell viewWithTag:1001];
    haed.tag = indexPath.row;
    NSLog(@"m_user_id:%@ fans_id:%@",m_user_id,famModel.fans_id);
    if ([m_user_id intValue] == [famModel.fans_id intValue]) {//modify by Scott
        [ibutton removeFromSuperview];
    }else{
        if (m_type == FANSTYPE) {
            if (famModel.fans_user_followed == 0) {
                [ibutton setTitle:@"关注" forState:UIControlStateNormal];
            }else if(famModel.fans_user_followed == 1){
                [ibutton setTitle:@"取消关注" forState:UIControlStateNormal];
            }
        }else{
            if (famModel.fans_user_followed == 0) {
                [ibutton setTitle:@"关注" forState:UIControlStateNormal];
            }else if(famModel.fans_user_followed == 1){
                [ibutton setTitle:@"取消关注" forState:UIControlStateNormal];
            }
        }
    }

    

    return tCell;
}
- (void)changeMydata:(id)data
{
    UIButton* ibutton = (UIButton*)data;
    NSLog(@"%d",ibutton.tag);
     FansAndAttentionListModel* famModel = [m_fadate objectAtIndex:ibutton.tag];
    if (famModel != nil) {
        MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
        tMainTabBar.m_TabbarCustom.hidden =YES;
        
        OwnViewController* tNextVC = [[OwnViewController alloc] initUesrID:famModel.fans_id];
        tNextVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tNextVC animated:YES];
        [tNextVC release];
    }

}
- (void)ChangeFButton:(UIButton*)ibutton
{
    MainTabBarController* tMainTabBar =(MainTabBarController*)self.navigationController.tabBarController;
    if (tMainTabBar.m_UserDic == nil) {
        LoginViewController* tLoginVC =[[LoginViewController alloc] init];
        UINavigationController* tNav =[tMainTabBar.viewControllers objectAtIndex:tMainTabBar.selectedIndex];
        tLoginVC.navigationItem.hidesBackButton =YES;
        tNav.hidesBottomBarWhenPushed =YES;
        [tNav pushViewController:tLoginVC animated:YES];
        [tLoginVC release];
    }else{
        NSLog(@"ib = %d",ibutton.tag);
        FansAndAttentionListModel* famModel = [m_fadate objectAtIndex:ibutton.tag];
        NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
        NSString* userid = [tUserDef stringForKey:@"user_id"];
        if ([ibutton.titleLabel.text isEqualToString:@"关注"]) {
            
            [[MyHttpProcessor sharedManager] RequestFollowGet:userid targe:famModel.fans_id type:1];
            [MyHttpProcessor sharedManager].delegate =self;
            [self addHudLoad];
            
        }
        else
        {
            [[MyHttpProcessor sharedManager] RequestFollowGet:userid targe:famModel.fans_id type:2];
            [MyHttpProcessor sharedManager].delegate =self;
            [self addHudLoad];
        }
        m_button = ibutton;
    }

}
#pragma mark -
#pragma mark MyHttpProcessorDelegate
- (void)OutFollow:(NSString*)_data
{
    [self hudWasHidden:nil];
    if (_data.intValue == 1) {
         if ([m_button.titleLabel.text isEqualToString:@"关注"])
         {
             [m_button setTitle:@"取消关注" forState:UIControlStateNormal];
         }else{
            [m_button setTitle:@"关注" forState:UIControlStateNormal];
         }
        m_button = nil;
    }else{
//        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
//        [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"errorMsg"] isCue:YES delayTime:3.0f];
    }
}
//粉丝
- (void)OutFansLisData:(NSMutableArray*)_data
{
    [self hudWasHidden:nil];
    NSUInteger num = [_data count];
    if (num == 0) {
        isPage = NO;
        return;
    }
    if (num < MAXPAGENUM) {
         isPage = NO;
    }else{
         isPage = YES;
         m_page++;
    }
    if ([m_fadate count]>0) {
        [m_fadate removeAllObjects];
    }
    for (int i = 0 ; i < num; ++i) {
        [m_fadate addObject:[_data objectAtIndex:i]];
    }
    [m_fandaTableView reloadData];
    [self doneLoadingTableViewData];
    isLook = YES;
}
//关注
- (void)OutAttentionListData:(NSMutableArray*)_data
{
    
    [self hudWasHidden:nil];
    NSUInteger num = [_data count];
    if (num == 0) {
        isPage = NO;
        return;
    }
    if (num < MAXPAGENUM) {
        isPage = NO;
    }else{
        isPage = YES;
    }
    if ([m_fadate count]>0) {
        [m_fadate removeAllObjects];
    }
    for (int i = 0 ; i < num; ++i) {
        [m_fadate addObject:[_data objectAtIndex:i]];
    }
    [m_fandaTableView reloadData];
    [self doneLoadingTableViewData];
    isLook = YES;
}

- (void)OurErrer:(NSDictionary*)dic
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"errorMsg"] isCue:YES delayTime:3.0f];
    [self hudWasHidden:nil];
    [self doneLoadingTableViewData];
    isLook = YES;
}
#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    m_MBHUD.delegate = nil;
	[m_MBHUD removeFromSuperview];
	[m_MBHUD release];
	m_MBHUD=nil;
}

-(void) addHudLoad{
	if (m_MBHUD == nil) {
		m_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:m_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		m_MBHUD.delegate = self;
		m_MBHUD.labelText = @"请求数据中...";
		[m_MBHUD show:YES];
	}
}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int tShowH =0;
    if ([scrollView isEqual:m_fandaTableView]) {
        [m_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
        tShowH = scrollView.contentOffset.y+scrollView.frame.size.height;
        if (tShowH > scrollView.contentSize.height+40&&isLook) {
            isNextAndUp = 1;
            [self Pagingrequest];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[m_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
    if (isPage) {
        isNextAndUp = 2;
        [self Pagingrequest];
    }else{
        [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.5f];
    }
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return m_reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	m_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	m_reloading = NO;
	[m_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:m_fandaTableView];
	
}

-(void)dealloc
{
    [m_TargetID release];
    [m_fandaTableView release];
    [_BackBttBarItem release];
    
    [m_fadate release];
     m_refreshHeaderView.delegate = nil;
    [m_refreshHeaderView release];
    [super dealloc];
}
@end
